<?php

/**
 * Category form.
 *
 * @package    tsantek-shop
 * @subpackage form
 * @author     Tomislav Šantek
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class CategoryForm extends BaseCategoryForm
{


  public function configure()
  {
      unset($this['lft'], $this['rgt'], $this['level'], $this['slug']);

$this->widgetSchema['root_id'] = new sfWidgetFormDoctrineChoice(array(
                'model' => 'category',
                'add_empty' => '~ (object is at root level)',
                'order_by' => array('lft', ''),
                'method' => 'getIndentedName'
        ));
    $this->setDefault('root_id', $this->object->getRootId());

    $this->setWidget('css_class', new sfWidgetFormChoice(array('choices'=>array('blue'=>'Plava', 'orange'=>'Narančasta'))));

    $this->widgetSchema->setLabel('root_id', 'Child of');
    $this->validatorSchema['root_id'] = new sfValidatorDoctrineChoice(array(
                    'required' => false,
                    'model' => 'category'
            ));

//    $this->validatorSchema['linked_to'] = new sfValidatorDoctrineChoice(array(
//                    'required' => false,
//                    'model' => 'category'
//            ));

    $this->setWidget('pic_path', new sfWidgetFormInputFileEditable(array(
            'file_src'    => '/uploads/category/'.$this->getObject()->pic_path,
            'edit_mode'   => !$this->isNew(),
            'is_image'    => true,
            'with_delete' => false,
      )));

    $this->setValidator('pic_path', new sfValidatorFile(array(
                    'mime_types' => 'web_images',
                    'path' => sfConfig::get('sf_upload_dir') . '/category',
                    'required' => false,
            )));
  }
	public function updateParentIdColumn($parentId)
	{
		$this->parentId = $parentId;
		// further action is handled in the save() method
	}

         protected function doSave($con = null)
	{
		parent::doSave($con);

		$node = $this->object->getNode();
                $this->rootId = $this->getValue('root_id');
//var_dump($this->rootId, $node->isValidNode()); die();
		if ($this->rootId != $this->object->getRootId() || !$node->isValidNode())
		{
			if (empty($this->rootId))
			{
				//save as a root
				if ($node->isValidNode())
				{
					$node->makeRoot($this->object['id']);
					$this->object->save($con);
				} else
				{
					$this->object->getTable()->getTree()->createRoot($this->object); //calls $this->object->save internally
				}
			} else
			{
				//form validation ensures an existing ID for $this->parentId
				$parent = $this->object->getTable()->find($this->rootId);
				$method = ($node->isValidNode() ? 'move' : 'insert') . 'AsLastChildOf';
				$node->$method($parent); //calls $this->object->save internally
                                $this->object->save($con);
			}
		}


	}
 

}
